package org.megha.blog.example.part9;

/**
 * A theatre that sells tickets.
 */
public class Theatre {

	int availableTickets;

	/** creates a new theatre with a fixed number of tickets */
	public Theatre(int availableTickets) {
		this.availableTickets = availableTickets;
	}

	/**
	 * Sells a ticket to the buyer.
	 *
	 * @return a unique ticket id representing the ticket sold
	 * @throws NoTicketsAvailableException when all tickets are sold out
         */
	public int buyTicket() throws NoTicketsAvailableException {
		if (availableTickets == 0) {
			throw new NoTicketsAvailableException();
		}
		return availableTickets--;
	}

	public static void main(String args[]) {
		// create a new threatre with only 3 seats/tickets
		Theatre theatre = new Theatre(3);

		for (int i = 1; i <= 5; i++) {
			try {
				int ticketId = theatre.buyTicket();
				System.out.println("Ticket #" + i + " is " + ticketId);
			} catch (NoTicketsAvailableException e) {
				System.out.println("Could not buy ticket #" + i);
			}
		}
	}
}
